<template>
    <el-button type="primary" :icon="ArrowLeft" circle @click="resetHandle" v-if="resetStatus" class="btn-abs"/>

    <VChart ref="chartRef" :option="options" @legendselectchanged="onLegendSelect" @click="handleChartClick"/>
</template>

<script setup>
import VChart from "vue-echarts";
import {use} from "echarts";
import {GridComponent, TooltipComponent} from "echarts/components";
import {BarChart} from "echarts/charts";
import {CanvasRenderer} from "echarts/renderers";
import {useTemplateRef} from "vue";
import {getSendPoliceBarOfJwApply, getSendPoliceBarOfJwApplyProvince} from "@/api/StatisticAnalysis/UseChart.js";
import useUserStore from "@/store/modules/user.js";
import dayjs from "dayjs";
import {ArrowLeft} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";


use([
    TooltipComponent,
    GridComponent,
    BarChart,
    CanvasRenderer
]);

const chartRef = useTemplateRef('chartRef');
const userUnit = useUserStore().info.unitId;
const timeStamp = dayjs().format('YYYY-MM-DD')
const router = useRouter();

// 回退数据
const resetStatus = ref(false)

// 图例名称
const legendName = {
    history: '历史数据',
    realtime: '实时数据'
}

const queryForm = reactive({
    unitId: userUnit,
    isUnit: true
})
// 当前图例
const currentLegend = ref(legendName.history)

const selectedLegend = ref({
    [legendName.history]: true,
    [legendName.realtime]: false,
});
// 是否省院数据
const isProvince = ref(false);
// 当前数据层级,默认1即第一层数据
const level = ref(1)
// 图表设置项
const options = ref({});
// 历史数据
const historyData = ref([]);
// 实时数据
const realTimeData = ref([]);
// 第二层数据
const secondData = ref([])
// 跳转的部门 id
const routeDeptId = ref(0)

// 获取数据
const getData = async () => {
    const history = await fetchChartData({endYear: timeStamp});
    historyData.value = history;

    realTimeData.value = await fetchChartData({endDate: timeStamp});

    // 默认历史
    setChartsData(
        history.map(item => item.deptName),
        history.reduce((prev, cur) => {
            prev.push({
                ...cur,
                name: cur.deptName,
                value: cur.counts
            })

            return prev;
        }, []),
    )
}
// 异步请求封装
const fetchChartData = async (params) => {
    const response = await getSendPoliceBarOfJwApply({...queryForm, ...params});
    return response.data || [];
};

onMounted(() => {
    getData()
})

// 设置图表数据
const setChartsDataByLegend = (seriesName, data, third = false) => {
    if (seriesName === legendName.history) {
        setChartsData(
            data.map(item => third ? item.dutyName : item.deptName),
            data.reduce((prev, cur) => {
                prev.push({
                    ...cur,
                    name: third ? cur.dutyName : cur.deptName,
                    value: cur.counts
                })

                return prev;
            }, []),
        )
    } else {
        setChartsData(
            data.map(item => third ? item.dutyName : item.deptName),
            [],
            data.reduce((prev, cur) => {
                prev.push({
                    ...cur,
                    name: third ? cur.dutyName : cur.deptName,
                    value: cur.counts
                })

                return prev;
            }, []),
        )
    }
}

// 设置图表数据
const setChartsData = (xData, historyData, realTimeData = []) => {
    options.value = {
        title: {
            text: '办案中心使用状态图',
            left: 'center',
            top: 0,
            right: 0,
            bottom: 0
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },
        legend: {
            data: ['历史数据', '实时数据'],
            left: 'right',
            itemGap: 10,
            selected: selectedLegend.value
        },
        grid: {
            left: 0,
            right: 0,
            top: 50,
            bottom: 20,
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xData,
            axisPointer: {
                type: 'shadow'
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '历史数据',
                type: 'bar',
                // tooltip: {
                //     valueFormatter: function (value) {
                //         return value + ' ml';
                //     }
                // },
                data: historyData
            },
            {
                name: '实时数据',
                type: 'bar',
                // tooltip: {
                //     valueFormatter: function (value) {
                //         return value + ' ml';
                //     }
                // },
                data: realTimeData
            }
        ]
    }
}


// 图例选择切换
const onLegendSelect = (event) => {
    // console.log(event);
    const {name} = event;
    // 只保持当前点击的 legend 选中，其他取消
    selectedLegend.value = {
        [legendName.history]: name === legendName.history,
        [legendName.realtime]: name === legendName.realtime,
    };
    options.value.legend.selected = selectedLegend.value;

    level.value = 1;
    isProvince.value = false;
    resetStatus.value = false;
    routeDeptId.value = 0;
    setChartsDataByLegend(name, name === legendName.history ? historyData.value : realTimeData.value);
}

// 柱状图点击事件
const handleChartClick = (events) => {
    // console.log(events, selectedLegend.value)
    const {name, seriesName, data} = events;
    if (events.type === 'click' && events.componentType === 'series') {

        if (level.value === 3) {
            const {EMAIL} = data
            console.log(data, EMAIL, seriesName)
            router.push({
                name: 'UseChartList',
                query: {
                    unitID: isProvince.value ? userUnit : routeDeptId.value,
                    dutyDept: EMAIL,
                    status: seriesName === legendName.history ? '4' : '1,2'
                }
            })
            return;
        }

        level.value += 1;
        switch (level.value) {
            case 2:
                if (name.includes('省院')) {
                    getProvinceData(seriesName, data)
                    level.value = 3
                    isProvince.value = true
                } else {
                    getSecondData(seriesName, data)
                }
                break;
            case 3:
                getProvinceData(seriesName, data)
                break;
        }
        // const query = seriesName === legendName.history ? {
        //     // unitId: data.deptId,
        //     endYear: timeStamp,
        // } : {
        //     // unitId: data.deptId,
        //     endDate: timeStamp
        // };
        //
        // if (name.includes('省院')) {
        //     await getProvinceData(seriesName, query)
        // } else {
        //     await getSecondData(seriesName, data)
        // }

        currentLegend.value = seriesName
        resetStatus.value = true
    }
};

// 获取第二层柱状图数据
const getSecondData = async (seriesName, data) => {
    const query = formatQuery(seriesName, data)

    const res = await getSendPoliceBarOfJwApply({
        ...queryForm,
        ...query
    })

    secondData.value = res.data
    setChartsDataByLegend(seriesName, res.data);
}

// 获取第三层省院数据
const getProvinceData = async (seriesName, data) => {
    const query = formatQuery(seriesName, data)
    routeDeptId.value = data.deptId
    const res = await getSendPoliceBarOfJwApplyProvince({
        ...queryForm,
        ...query
    });

    setChartsDataByLegend(seriesName, res.data, true)
}

// 处理请求参数
const formatQuery = (seriesName, data) => {
    return seriesName === legendName.history ? {
        unitId: data.deptId,
        endYear: timeStamp
    } : {
        unitId: data.deptId,
        endDate: timeStamp
    }
}
// 回退数据处理
const resetHandle = () => {
    switch (level.value) {
        case 3:
            // 省院数据直接回第一层
            if (isProvince.value) {
                level.value = 1;
                resetStatus.value = false;
                setChartsDataByLegend(
                    currentLegend.value,
                    currentLegend.value === legendName.history ? historyData.value : realTimeData.value
                )
            } else {
                setChartsDataByLegend(
                    currentLegend.value,
                    secondData.value
                )
                level.value -= 1;
            }
            break;
        case 2:
            setChartsDataByLegend(
                currentLegend.value,
                currentLegend.value === legendName.history ? historyData.value : realTimeData.value
            )
            resetStatus.value = false;
            level.value -= 1;
            break;
    }
    // setChartsDataByLegend(currentLegend.value, currentLegend.value === legendName.history ? historyData.value : realTimeData.value)
}
</script>

<style scoped lang="scss">
.btn-abs {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 33;
}
</style>